﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;

namespace Tesla.Graphics {
    /// <summary>
    /// Represents a complete set of shaders on the device used to render geometry.
    /// An effect is made up of individual vertex/pixel shaders and 1 or more
    /// techniques that use them. Each technique in turn has a set of 1 or more passes.
    /// </summary>
    public class Effect : GraphicsResource, ISavable {
        private EffectImplementation _impl;
        private byte[] _cachedByteCode;

        /// <summary>
        /// Gets the underlying effect implementation.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets or sets the currently active technique.
        /// </summary>
        public IEffectTechnique CurrentTechnique {
            get {
                return _impl.CurrentTechnique;
            }
            set {
                _impl.CurrentTechnique = value;
            }
        }

        /// <summary>
        /// Gets the technique collection owned by the effect.
        /// </summary>
        public IEffectTechniqueCollection Techniques {
            get {
                return _impl.Techniques;
            }
        }

        /// <summary>
        /// Gets the collection of uniform effect parameters.
        /// </summary>
        public IEffectParameterCollection Parameters {
            get {
                return _impl.Parameters;
            }
        }

        //For Clone
        private Effect(EffectImplementation implementation) {
            _impl = implementation;
        }

        //For ISavable
        private Effect() {}

        /// <summary>
        /// Creates a new Effect from the specified compiled shader byte code.
        /// </summary>
        /// <param name="shaderByteCode">Compiled byte code</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying effect implementation fails.</exception>
        public Effect(byte[] shaderByteCode) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateEffectImplementation(shaderByteCode);
                _cachedByteCode = shaderByteCode;
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new Effect from the specified compiled shader byte code.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="shaderByteCode">Compiled byte code</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the render system is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying state implementation fails.</exception>
        public Effect(IRenderSystemProvider renderSystem, byte[] shaderByteCode) {
            if(renderSystem == null) {
                Dispose();
                throw new ArgumentNullException("renderSystem", "Render system cannot be null.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateEffectImplementation(shaderByteCode);
                _cachedByteCode = shaderByteCode;
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="Effect"/> is reclaimed by garbage collection.
        /// </summary>
        ~Effect() {
            Dispose(false);
        }

        /// <summary>
        /// Clones the effect. This creates a new unique instance of the effect.
        /// </summary>
        /// <returns></returns>
        public Effect Clone() {
            Effect clone = new Effect(_impl.Clone());
            clone.RenderSystem = base.RenderSystem;
            clone._cachedByteCode = _cachedByteCode;
            return clone;
        }

        /// <summary>
        /// Serializes this Effect.
        /// </summary>
        /// <param name="output">Output to write to</param>
        public void Write(ISavableWriter output) {
            output.Write("Name", _impl.Name);
            output.Write("EffectCode", _cachedByteCode);
        }

        /// <summary>
        /// Deserializes this Effect.
        /// </summary>
        /// <param name="input">Input to read from</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying effect implementation fails or the render
        /// system is not set.</exception>
        public void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            String name = input.ReadString();
            _cachedByteCode = input.ReadByteArray();

            try {
                _impl = renderSystem.CreateEffectImplementation(_cachedByteCode);
                _impl.Name = name;
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }
    }
}
